package com.www.applyword.ui.my;

import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.alipay.sdk.app.PayTask;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.www.applyword.Constants.Constants;
import com.www.applyword.R;
import com.www.applyword.adapter.RechargeAdapter;
import com.www.applyword.base.BaseActivity;
import com.www.applyword.bean.PayResult;
import com.www.applyword.bean.RechargeListBean;
import com.www.applyword.bean.ResultBean;
import com.www.applyword.bean.WXPayBean2;
import com.www.applyword.event.EventConstants;
import com.www.applyword.event.MessageEvent;
import com.www.applyword.http.CallBack;
import com.www.applyword.http.HttpClient;
import com.www.applyword.utils.SPUtil;
import com.www.applyword.utils.Utils;
import com.www.applyword.view.MyGridView;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * author : huang
 * date   : 2019/11/14 0014 18:02
 * version: 1.0
 */
public class RechargeActivity extends BaseActivity {
    @BindView(R.id.gv)
    MyGridView mGridView;
    @BindView(R.id.et_input_recharge_money)
    EditText etInputRechargeMoney;
    @BindView(R.id.iv_alipay)
    ImageView ivAlipay;
    @BindView(R.id.iv_alipay_yes)
    ImageView ivAlipayYes;
    @BindView(R.id.rl_alipay_pay)
    RelativeLayout rlAlipayPay;
    @BindView(R.id.iv_wechat)
    ImageView ivWechat;
    @BindView(R.id.iv_wechat_yes)
    ImageView ivWechatYes;
    @BindView(R.id.rl_wechat_pay)
    RelativeLayout rlWechatPay;

   private List<RechargeListBean.RechargeListBean2> rechargeList  = new ArrayList<>();
    private RechargeAdapter mProvinceAdapter;
    private int payType = 3;
    public IWXAPI mWxApi;
    private  Map<Integer, String> map = new HashMap<>();


    @Override
    protected void loadViewLayout() {
        setContentView(R.layout.recharge_activity);
        setTitle("充值");
        setRringTitle("确认");
        mWxApi = WXAPIFactory.createWXAPI(this, Constants.WECHAT_ID, false);
        mWxApi.registerApp(Constants.WECHAT_ID);
        tv_right.setOnClickListener(v -> {
            if (TextUtils.isEmpty(etInputRechargeMoney.getText().toString().trim())){
                Utils.showToastSafe("请输入充值金额");
                return;
            }
            if (payType == 3){
                Utils.showToastSafe("请选择支付方式");
                return;
            }
            Map<String, Object> params = new HashMap<>();
            params.put("Record_UserID", SPUtil.getString(Constants.USERID));
            params.put("Record_Money", etInputRechargeMoney.getText().toString().trim());
            params.put("Record_Type", payType + "");
            params.put("Record_RecordType", "0");
            if (payType == 1){
                HttpClient.post(RechargeActivity.this, Constants.ADDRECORD, params,new CallBack<WXPayBean2>() {
                    @Override
                    public void onSuccess(WXPayBean2 wayPay) {
                        if (wayPay.Status == 1){
                            PayReq req = new PayReq();
                            req.appId = wayPay.Result.appId;
                            req.partnerId = wayPay.Result.partnerId;
                            req.prepayId = wayPay.Result.prepayId;
                            req.nonceStr = wayPay.Result.nonceStr;
                            req.timeStamp = wayPay.Result.timeStamp;
                            req.packageValue = wayPay.Result.packageValue;
                            req.sign = wayPay.Result.sign;
                            req.extData = "0.02";
                            mWxApi.sendReq(req);
                        }
                    }
                });
            }else {
                HttpClient.post(RechargeActivity.this, Constants.ADDRECORD, params,new CallBack<ResultBean>() {
                    @Override
                    public void onSuccess(ResultBean resultBean) {
                        if (resultBean.Status == 1) {
                            Runnable payRunnable = new Runnable() {
                                @Override
                                public void run() {
                                    PayTask alipay = new PayTask(RechargeActivity.this);
                                    PayResult payResult = new PayResult((Map<String, String>) alipay.payV2(resultBean.Result, true));
                                    /**
                                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                                     */
                                    final String resultStatus = payResult.getResultStatus();// 同步返回需要验证的信息
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            // 判断resultStatus 为9000则代表支付成功
                                            if (TextUtils.equals(resultStatus, "9000")) {
                                                // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                                                MessageEvent messageEvent = new MessageEvent();
                                                messageEvent.setMessageKey(EventConstants.PAY);
                                                EventBus.getDefault().post(messageEvent);
                                                Utils.showToastSafe("充值成功");
                                                // Toast.makeText(RechargeActivity.this, "充值成功", Toast.LENGTH_SHORT).show();
                                                finish();
                                            } else {
                                                // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                                                Utils.showToastSafe("支付失败");
                                                finish();
                                            }
                                        }
                                    });
                                }
                            };
                            // 必须异步调用
                            Thread payThread = new Thread(payRunnable);
                            payThread.start();
                        }
                    }
                });
            }
        });
    }


    @Override
    protected void loadData() {
        mProvinceAdapter = new RechargeAdapter(this, rechargeList);
        mGridView.setAdapter(mProvinceAdapter);
        mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Button button =  view.findViewById(R.id.bt);
                if (button.isSelected() == false){
                    button.setSelected(true);
                   // map.put(position,rechargeList.get(position).getRecharge_Money() + "");//添加
                    etInputRechargeMoney.setText(rechargeList.get(position).getRecharge_Money() + "");
                    etInputRechargeMoney.setSelection(etInputRechargeMoney.getText().length());
                }else {
                    button.setSelected(false);
                }
            }
        });


        Map<String, Object> params = new HashMap<>();
        HttpClient.get(RechargeActivity.this, Constants.GETRECHARGELIST, params,new CallBack<RechargeListBean>() {
            @Override
            public void onSuccess(RechargeListBean rechargeListBeans) {
                rechargeList.clear();
                rechargeList.addAll(rechargeListBeans.Result);
                mProvinceAdapter.notifyDataSetChanged();
            }
        });
    }



    @OnClick({R.id.rl_alipay_pay, R.id.rl_wechat_pay})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_alipay_pay:
                payType = 0;
                ivAlipayYes.setImageResource(R.mipmap.select_people_click);
                ivWechatYes.setImageResource(R.mipmap.select_people_normal);
                break;
            case R.id.rl_wechat_pay:
                 payType = 1;
                ivWechatYes.setImageResource(R.mipmap.select_people_click);
                ivAlipayYes.setImageResource(R.mipmap.select_people_normal);
                break;
                default:
        }
    }
}
